package net.stock.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.stock.utils.StockUtils;
import net.stock.db.StockItem;
import net.stock.service.StockDao;
import net.stock.service.StockService;

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Collection;
import java.io.IOException;

/**
 * @author naim
 * @date Dec 31, 2009
 */
@Controller("/ajax")
public class AjaxRequestController {
    private Logger log = Logger.getLogger(getClass().getName());

    @Autowired
    private StockDao stockDao;

    @Autowired
    private StockService stockService;

    @RequestMapping(method = RequestMethod.GET, value = "/refresh")
    public ModelAndView refresh(HttpServletRequest request, ModelMap model) {
        String userEmail = StockUtils.getLoggedUserEmail(request);
        log.log(Level.INFO, "Reading StockItems for user: " + userEmail);

        Collection<StockItem> stockItems = stockDao.getStockItems(userEmail);
        String jsonString = stockService.getPriceOnJson(stockItems);
        return new ModelAndView(new JsonView(jsonString));
    }
}
